package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 验证码Controller
 */
@RestController
@RequestMapping("/mobile/validateCode")
@Slf4j
public class MobileValidateCodeController {
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/send")
    public Result send(String type, String telephone) {

        //判断是否已经生成验证码,如果已经有了就把原来的直接删除
        Object redisCode = redisTemplate.opsForValue().get(RedisConst.VALIDATE_CODE_PREFIX + type + ":" + telephone);
        if(redisCode!=null){
            redisTemplate.delete(RedisConst.VALIDATE_CODE_PREFIX+type+":"+telephone);
        }
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //调用阿里云接口api
//      SMSUtils.sendMessage("签名","模板","手机号","验证码");
        System.out.println("验证码:" + code);

        //把验证码存入redis中，设置过期时间5分钟
        redisTemplate.opsForValue().set(RedisConst.VALIDATE_CODE_PREFIX+type+":"+telephone,code,5,TimeUnit.MINUTES);
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }
}
